package com.learn.window;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.util.ArrayList;

/**
 * @create: 2023-04-19 15:35
 * @author: Mr.Du
 * --------------
 * @notes: 滑动窗口案例
 **/
public class SlidingTimeWindowDemo {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> streamSource = env.socketTextStream("node1", 9999);

        SingleOutputStreamOperator<Tuple2<String, Integer>> mapStream = streamSource
                .map(line -> Tuple2.of(line, 1)).returns(Types.TUPLE(Types.STRING,Types.INT));

        //由于未经过keyBy，所以统计的是窗口内的全量数据
        mapStream
                .windowAll(SlidingProcessingTimeWindows.of(Time.seconds(10),Time.seconds(5)))
                .sum(1).print("SlidingTimeWindowAll>>>>");

        mapStream
                .keyBy(0)
                .window(SlidingProcessingTimeWindows.of(Time.seconds(10),Time.seconds(5)))
                .sum(1).print("KeyBy-slidingProcessTimeWindow>>>>");

        mapStream.keyBy(0).sum(1).print("全累计出现的值》》》》》》》");

        env.execute();
    }
}
